<?php

class DBSessionLogger extends DryAbstractLogger {
	
	/**
	 * Instance variable - for singleton pattern
	 * @var object
	 */
	private static $instance = null;
	
	/**
	 * Path to the logs directory
	 * @var string
	 */
	private $logDir;
	
	
	protected $logFileNameBase = "db_session_handler.log";
	
	/**
	 * Full path to the log file
	 * @var string
	 */
	private $logPath;
	
	/**
	 * Log file resource
	 * @var unknown_type
	 */
	private $logHandle;
	
	/**
	 * Default log directory
	 * @var string
	 */
	const VARLOG_DIR = "/var/log/";  
	
	/**
	 * Private constructor - to enforce the singleton pattern
	 */
	private function __construct() {
		
	}
	
	/**
	 * carries out the singleton pattern
	 * @param string $pHandlerPrefix
	 */
	public static function getInstance($pHandlerPrefix = null) {
		if (is_null(self::$instance)) {
			self::$instance = self::makeInstance($pHandlerPrefix);
		}
		return self::$instance;
	}
	
	
	/**
	 * Creates and configures the instance of the logger
	 * @param string $pHandlerPrefix
	 */
	private static function makeInstance($pHandlerPrefix = null) {
		$obj = new DBSessionLogger(); 
		//set log dir:
		if (class_exists('Conf') == true && !is_null(Conf::get('LOG_DIR')) && is_dir(Conf::get('LOG_DIR')) && is_writable(Conf::get('LOG_DIR')) ) {  //if log dir is configured and is writable
			$obj->logDir = Conf::get('LOG_DIR');
			$dirSepLength = strlen(DIRECTORY_SEPARATOR);
			if (substr($obj->logDir, -1 * $dirSepLength ) !== DIRECTORY_SEPARATOR ) {
				$obj->logDir = $obj->logDir . DIRECTORY_SEPARATOR;
			}
		}
		 else { // log dir IS NOT configured.  
		 	  if (is_dir(self::VARLOG_DIR) && is_writable(self::VARLOG_DIR)) {
		 	  	$obj->logDir = self::VARLOG_DIR;
		 	  }
		 }
		 
		 //set log file:
		 if (!is_null($pHandlerPrefix)) {
		 	 $obj->logPath = $obj->logDir . $pHandlerPrefix . "_" . $obj->logFileNameBase;
		 }
		  else {
		  	$obj->logPath =  $obj->logDir . $obj->logFileNameBase;
		  }
		  
		//check if log file is writable:
		$obj->logHandle = @fopen($obj->logPath, "a");
		if ($obj->logHandle == false) {
			//echo "Failed to open the log file [".$obj->logPath."] for writing." . PHP_EOL;
			//echo "Log messages will be sent to the STD_OUT" . PHP_EOL;
		}   
		return $obj; 
	}
	
	public function log( $pMsg, $pTime = null, $pFile = null, $pLine = null ) {
		$str = "[".date("m/d/Y H:i")."] " . $pMsg . PHP_EOL;
		if ($this->logHandle) return fwrite($this->logHandle, $str);
		return null;
	}
	
	public function logException(Exception $e) {
		$msg = get_class($e). " has been thrown at " . $e->getLine() . ":" . $e->getFile(). "[".$e->getMessage()."]";
		$msg .= "\nStack trace: " . $e->getTraceAsString();
		
		return $this->log( $msg );
	}
}